<template>
    <div class="container-main" v-infinite-scroll="load" :infinite-scroll-disabled="disabled"
        :infinite-scroll-distance="60">
        <div class="category">
            <div class="inner">
                <div v-for="item in categoryList" :key="item.id">
                    <div :class="page.category.includes(item.id) ? 'mytag-select mytag' : 'mytag'"
                        @click="handleCategory(item.id)">{{ item.name }}</div>
                </div>
                <!-- <el-popover v-for="item in categoryList" :key="item.id" placement="bottom" :title="item.name"
                    :width="200" trigger="hover" :content="item.remark">
                    <template #reference>
                        <div :class="page.category.includes(item.id) ? 'mytag-select mytag' : 'mytag'"
                            @click="handleCategory(item.id)">{{ item.name }}</div>
                    </template>
</el-popover> -->
            </div>
            <div class="inner" style="width:100%;justify-content: flex-end;">
                <div style="margin-right:10px;" title="排序" @click="() => pageHandle('desc')">
                    <el-tag type="primary">
                        <el-icon v-if="page.desc == '1'">
                            <SortDown />
                        </el-icon>
                        <el-icon v-else>
                            <SortUp />
                        </el-icon>
                    </el-tag>
                </div>
                <el-radio-group v-model="page.type" size="small" @change="() => pageHandle('type')">
                    <el-radio-button label="时间" value="2" />
                    <el-radio-button label="热度" value="1" />
                </el-radio-group>
            </div>
        </div>
        <div v-show="!loadingInit" class="top">
            <el-carousel class="first-item">
                <el-carousel-item style="height: 450px;" v-for="item in mainList" :key="item.id">
                    <!-- <h3 class="small justify-center" text="2xl">{{ item }}</h3> -->
                    <img style="width: 100%;height:100%" :src="srcToPath(item.image)" :alt="item.title"
                        :title="item.title" @click="toPath(item.url)">
                </el-carousel-item>
            </el-carousel>
            <div class="item" v-for="item in articleList" :key="item.id" @click="toArticleDetils(item.id)">
                <div>
                    <img :src="item.cover.includes('http') ? item.cover : baseUrl + '/' + item.cover" :alt="item.title"
                        :title="item.title" />
                </div>
                <p class="title" v-html="highlightKeyword(item.title)"></p>
                <span class="clamp" style="text-overflow: ellipsis;" v-html="highlightKeyword(item.summary)"></span>
                <p class="username">{{formatDate(item.createdAt) }} · {{ item.username }}</p>
                
            </div>
        </div>
        <loadingView v-if="loadingInit"></loadingView>
        <p v-if="loading" class="endText">Loading...</p>
        <p v-if="noMore" class="endText">No more</p>
    </div>
</template>
<script setup>
import loadingView from '@/components/loading.vue'
import { ref, unref, computed } from 'vue'
import { getCategory, getArticlePage, userMain } from '@/api/main'
import { useRouter } from 'vue-router';
import formatDate from '@/utils/formatDate'
import { baseUrl } from '@/utils/http.js'
import srcToPath from '@/utils/srcToPath.js'
// const maxLength = 20
const router = useRouter()
const categoryList = ref([])
// 文章详情信息 desc 1倒序  type 排序类型 1热度/2时间  category分类
const page = ref({
    pageSize: 20,
    pageNum: 1,
    type: '1',
    desc: '0',
    total: 0,
    category: [],
    keywords: '',
})
const articleList = ref([])
const pageHandle = (e) => {
    if (e == 'desc') {
        if (page.value[e] == '1') {
            page.value[e] = '0'
        } else {
            page.value[e] = '1'
        }
    }
    page.value.pageNum = 1
    articleList.value = []
    loadingInit.value = true
    getArticl()
}
const loadingInit = ref(true)
const mainList = ref([])
const init = async () => {
    page.value.keywords = !localStorage.getItem('keywords') ? '' : localStorage.getItem('keywords')
    // 分类列表
    const category = await getCategory()
    categoryList.value = category.data
    getArticl()
    console.log(articleList.value);

    const { data } = await userMain()
    mainList.value = data
    console.log(mainList);
}

const getArticl = async () => {
    const article = await getArticlePage({ ...unref(page) })
    articleList.value = [...articleList.value, ...article.data.data]
    page.value.total = article.data.total
    console.log(page.value);
    loading.value = false
    setTimeout(() => {
        loadingInit.value = false
    }, 300)
}

// 滚动加载
const loading = ref(true)
const noMore = computed(() => articleList.value.length >= page.value.total)
const disabled = computed(() => loading.value || noMore.value)
const load = () => {
    console.log("调用", articleList.value.length, page.value.total);
    loading.value = true
    setTimeout(() => {
        page.value.pageNum++;
        getArticl()
        loading.value = false
    }, 2000)
}
// 文章主页
const toArticleDetils = (id) => {
    console.log(window.location.hostname);
    const url = `http://${window.location.host}${window.location.hash.includes('#') ? '/#' : ''}/article/${id}`; // 替换为你要打开的页面的路径  
    window.open(url, '_blank'); // '_blank' 表示在新窗口或新标签页中打开
}

const toPath = (url) => {
    window.open(url, '_blank'); // '_blank' 表示在新窗口或新标签页中打开
}

// 选中分类
const handleCategory = (e) => {
    if (page.value.category.includes(e)) {
        page.value.category = page.value.category.filter(item => item != e)
    } else {
        page.value.category.push(e)
    }
    page.value.pageNum = 1
    articleList.value = []
    loadingInit.value = true
    // 重新获取列表数据
    getArticl()
}


// 关键字高亮
function highlightKeyword(str) {
    const keywords = page.value.keywords.split(' ')
    // 遍历关键字数组  
    for (let keyword of keywords) {
        if (!keyword || keyword.length == 0) {
            continue
        }
        // 使用正则表达式来查找并替换当前关键字  
        // 确保关键字在正则表达式中作为字面量字符串，避免特殊字符的干扰  
        const regex = new RegExp(escapeRegExp(keyword.replace(/\s*/g, "")), 'gi');
        str = str.replace(regex, `<span style="color: #ff7866;font-weight: bold;">$&</span>`);
    }
    return str;
}

// 由于关键字可能包含正则表达式特殊字符，我们需要一个函数来转义它们  
function escapeRegExp(string) {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& 表示匹配到的内容  
}
init()



// 导入Store

</script>

<style lang="scss" scoped>
.container-main {
    box-sizing: border-box;
    padding: 20px calc((100vw - 1400px) / 2);
    padding-bottom: 0;
    width: 100%;
    overflow: auto;
    height: calc(100vh - 60px);

    @media (max-width: 600px) {
        height: calc(100vh - 100px);
    }

    .top {
        display: grid;

        /*grid-column: span 4;
        grid-column-start: span 4;
        grid-column-end: auto;

        grid-template-columns: repeat(4, 1fr) ;*/


        grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
        /* 假设我们想要列平分 */
        grid-gap: 20px;
        /* 设置网格间隙 */
        grid-auto-rows: minmax(100px, auto);
        /* 设置自动行的最小和最大高度 */

        .first-item {
            /* 跨越两行两列 */
            grid-row: 1 / 3;
            /* 跨越两行 */
            grid-column: 1 / 3;
            /* 跨越两列 */
            height: 80%;
        }

        .item {
            height: 100%;
            display: flex;
            flex-direction: column;
            gap: 5px;
            img {
                position: relative;
                display: inline-block;
                line-height: 1;
                width: 100%;
                height: 150px;
                vertical-align: middle;
            }

            // border: 1px #333 solid;

        }

        .title {
            padding: 4px 0;
            font-size: 16px;
            color: var(--el-text-color-primary);
            display: -webkit-box;
            overflow: hidden;
            -webkit-box-orient: vertical;
            text-overflow: -o-ellipsis-lastline;
            text-overflow: ellipsis;
            word-break: break-word !important;
            word-break: break-all;
            line-break: anywhere;
            -webkit-line-clamp: 1;
            margin: 0;
        }

        .clamp {
            width: 100%;
            position: relative;
            // display: -webkit-box;
            // -webkit-box-orient: vertical;
            // overflow: hidden;
            // line-height: 1.5em;
            // /* 根据你的字体和行高调整 */
            // max-height: 3em;
            // /* 最多显示2行，根据你的行高调整 */
            // text-overflow: ellipsis;
            display: -webkit-box;
            overflow: hidden;
            -webkit-box-orient: vertical;
            text-overflow: -o-ellipsis-lastline;
            text-overflow: ellipsis;
            word-break: break-word !important;
            word-break: break-all;
            line-break: anywhere;
            -webkit-line-clamp: 2;
            font-size: 12px;
            color: var(--el-text-color-regular);
            height: 32px;
        }

        .clamp::after {
            // content: "...";
            // position: absolute;
            // bottom: 0;
            // right: 0;
            // padding-left: 40px;
            // width: 10%;
            // text-align: right;
            /* 根据你的需要调整省略号的位置 */
            // background: linear-gradient(to right, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1) 50%);
        }

        .username {
            margin: 0;

            padding: 4px 0;
            font-size: 12px;
            color: var(--el-text-color-regular);
        }
    }

    @media (max-width: 1400px) {
        padding: 20px;
    }

    @media (max-width: 600px) {
        padding: 20px;

        /* 减去间隙后的宽度 */
        .top {
            grid-gap: 0px;
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            align-items: start;
            /*   // grid-template-columns: 1fr; 当屏幕小于800px时，只设置一列 */
        }

        .first-item {
            width: 100%;
        }

        .item {
            width: 48%;
            margin: 1%
        }

    }



}

.el-carousel__item h3 {
    color: #475669;
    opacity: 0.75;
    line-height: 150px;
    margin: 0;
    text-align: center;
}

.el-carousel__item:nth-child(2n) {
    background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
    background-color: #d3dce6;
}

.category {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: center;
    min-height: 40px;

    .mytag {
        padding: 5px 16px;
        font-size: 14px;
        border-radius: 10px;
        color: var(--el-color-info);
        border: .5px solid var(--el-color-info);
    }

    .mytag-select {
        padding: 5px 16px;
        font-size: 14px;
        border-radius: 10px;
        color: var(--el-color-primary);
        border: .5px solid var(--el-color-primary);
    }

    .mytag+.mytag {
        margin-right: 10px;
    }

    .mytag:first-child {
        margin-right: 10px;
    }
}

.inner {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    // justify-content: start;
    gap: 10px;
    padding-bottom: 10px;
}

.endText {
    text-align: center;
    padding: 15px;
    color: var(--el-text-color-regular);
}

:v-deep .el-carousel__container {
    height: 450px !important;
}

:v-deep .highlight {
    color: #ff7866;
    font-weight: bold;
}
</style>
